package com.leyou.auth.task;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.AppInfo;
import com.leyou.auth.entity.ApplicationInfo;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AppTokenHolder {

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;

    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;

    @Autowired
    private JwtProperties prop;

    @Autowired
    private ApplicationInfoMapper applicationInfoMapper;

    private String token;

    // 每隔24小时去申请一次token
    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void loadTokenTask() throws InterruptedException {
        try {
            // 封装载荷
            AppInfo appinfo = new AppInfo();
            appinfo.setId(prop.getApp().getId());
            appinfo.setServiceName(prop.getApp().getName());
            // 授权中心具有访问其他微服务的id的集合
            appinfo.setTargetList(applicationInfoMapper.queryTargetIdList(prop.getApp().getId()));
            // 申请了token
            this.token = JwtUtils.generateTokenExpireInMinutes(appinfo, prop.getPrivateKey(), prop.getApp().getExpire());
            log.info("【auth微服务】申请token成功");
        } catch (Exception e) {
            log.error("【auth微服务】申请token失败：{}", e.getMessage());
        }
    }

    // 获取token
    public String getToken(){
        return token;
    }

}
